package com.hngy.xpq.chatdemo.adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hngy.xpq.chatdemo.R;
import com.hngy.xpq.chatdemo.bean.Chat;

import java.util.Calendar;
import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {

    private List<Chat> listData;
    private int width;   // 屏幕宽度

    static class ViewHolder extends RecyclerView.ViewHolder {

        View view;
        ImageView image;
        TextView name, time, text;

        public ViewHolder(View itemView) {
            super(itemView);
            view = itemView;
            image = itemView.findViewById(R.id.chatImage);
            name = itemView.findViewById(R.id.chatName);
            time = itemView.findViewById(R.id.chatTime);
            text = itemView.findViewById(R.id.chatText);
        }
    }

    // 获取到数据
    public ChatAdapter(List<Chat> list, int width) {
        this.listData = list;
        this.width = width;
    }

    @NonNull
    @Override
    public ChatAdapter.ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat,parent,false);
        final ChatAdapter.ViewHolder holder = new ChatAdapter.ViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ChatAdapter.ViewHolder holder, int position) {
        // 数据绑定
        final Chat data = listData.get(position);
        holder.name.setText(data.getNotes());
        holder.time.setText(data.getTime());
        // 处理 预文本
        holder.text.setText(handleText(data.getNext()));
        // 图片
        holder.image.setImageResource(Integer.valueOf(data.getImage()));
    }

    /**
     * 防止文本过长，影响字体美观
     * @param text
     * @return
     */
    private String handleText(String text) {
        int endIndex = width/90;
        // 根据屏幕宽度，截取预显示文字
        String string = text;
        if (string.length() > endIndex) {
            string = string.substring(0, endIndex) + "...";
        }
        return string;
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

}

